<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Crypt;
use DB;

class UserController extends Controller
{
    // public function __construct()
    // {
    //     $this -> middleware('login');
    // }
    //用户添加add
    public function add()
    {
      return view('home.user.add', ['title' => '用户添加']);
    }

    public function insert(Request $request)
    {
    	// $data = $request -> all();
    	// dd($data);
        $this->validate($request, [
            'password' => 'required',
            'repassword' => 'same:password',
            'email' => 'email',
        ], [
            'email.required' => '用户名不能为空',
            'password.required' => '密码不能为空',
            'repassword.same' => '密码不一致',
            'email' => '邮箱格式不正确',
        ]);

        $data = $request -> except('_token');
        // 处理密码字段
        $str = Crypt::encryptString($data['password']);
        $userData['password'] = $str;
        $userData['email'] = $data['email'];
        $userData['token'] = str_random(50);
        $userData['airline'] = 0;
        $userData['status'] = 0;
        $time = date('Y-m-d H:i:s');
        $userData['created_at'] = $time;
        $userData['updated_at'] = $time;
        $userData['name'] = '';
        $userData['phone'] = '';

        // 添加数据
        $userId = DB::table('users') -> insertGetId($userData);

        if($userId)
        {
            $userInfoData['user_id'] = $userId;
            $userInfoData['created_at'] = $time;
            $userInfoData['updated_at'] = $time;
            $userInfoData['pic'] = '';

            $res = DB::table('users_info') -> insert($userInfoData);

            if($res)
            {
                return redirect('/home/login') -> with(['info' => '注册成功']);
            }else
            {
                return back() -> with(['info' => '注册失败']);
            }
        }
    }


}
